<template>
  <div class="util">
   
	<el-icon style="margin-left: 3%;"><parkingVue /></el-icon>
    <el-tag>车位统计</el-tag>
    <el-tag>车位处理</el-tag>
    <el-input type="text"
      placeholder="请输入用户查询车位" 
      v-model="input"
      style="width: 300px;height: 35px;margin-top: 20px;
      margin-bottom: 20px;margin-left: 50%;"/>
    <el-button :icon="Search" style="margin-left: 5px;margin-bottom: 6px;" circle @click="search" />
  </div>
  <div class="main">
    <div class="main1" >
      <!-- 区域选择下拉框 -->
      <div style="margin-bottom: 20px; margin-left: 0;width:200px">
        <el-select v-model="selectedArea" placeholder="请选择区域" @change="handleAreaChange">
          <el-option
            v-for="area in areas"
            :key="area.value"
            :label="area.label"
            :value="area.value">
          </el-option>
        </el-select>
      </div>
      
      <!-- 左右布局容器 -->
      <div class="chart-container" style="width: 100%; height: 100%;">
        <!-- 左侧：图表 -->
        <div class="chart-left" >
          <div id="parkingChart" style="width: 100%; height: 360px;"></div>
        </div>
        <!-- 右侧：筛选区域-->
        <div class="main3">
          <el-col :span="24">
            <h1>已用车位/总车位数</h1>
            <el-statistic :value="count">
              <template #suffix>/{{ totalParkingSpaces }}</template>
            </el-statistic>
            
            <el-row :gutter="10">
              <el-col :span="20">
                <el-col>
                  <!-- 已占用车位 -->
                  <el-row :span="10">
                    <h1>已占用车位</h1>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <template v-if="main.used.length > 0">
                        <div class="tags-container">
                          <el-tag 
                            v-for="(item, index) in main.used" 
                            :key="index"
                            type='warning' 
                            style="--el-tag-text-color:black; margin: 4px;"
                            class="车位">
                            {{ item }}
                          </el-tag>
                        </div>
                      </template>
                      <template v-else>
                        <div>无</div>
                      </template>
                    </el-col>
                  </el-row>
                  
                  <!-- 空闲中车位 -->
                  <el-row :span="10" style="margin-top:5px">
                    <h1>空闲中车位</h1><br />
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <template v-if="main.kong.length > 0">
                        <div class="tags-container">
                          <el-tag 
                            v-for="(item, index) in main.kong" 
                            :key="index"
                            type='warning' 
                            style="--el-tag-text-color:black; margin: 4px;"
                            class="车位">
                            {{ item }}
                          </el-tag>
                        </div>
                      </template>
                      <template v-else>
                        <div>无</div>
                      </template>
                    </el-col>
                  </el-row>
                  
                  <!-- 审核中车位 -->
                  <el-row :span="10">
                    <h1>审核中车位</h1>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <template v-if="main.wait.length > 0">
                        <div class="tags-container">
                          <el-tag 
                            v-for="(item, index) in main.wait" 
                            :key="index"
                            type='warning' 
                            style="--el-tag-text-color:black; margin: 4px;"
                            class="车位">
                            {{ item }}
                          </el-tag>
                        </div>
                      </template>
                      <template v-else>
                        <div>无</div>
                      </template>
                    </el-col>
                  </el-row>
                </el-col>
              </el-col>
            </el-row>
          </el-col>
        </div>
      </div>
    </div>
    <div class="main2" >
      <el-table :data="tableData.records" 
        height="350" style="width: 100%;" 
        :header-cell-style="{background:'#F3F4F7',color:'#555',}">
        <el-table-column label="用户" prop="username" align="center" ></el-table-column>
        <el-table-column label="车位" prop="content" align="center" ></el-table-column>
        <el-table-column label="车牌" prop="carNumber" align="center" ></el-table-column>
        <el-table-column label="状态"  align="center" >
          <template #default="scope">
            <el-tag type="danger" v-if="scope.row.occupied==1">未审核</el-tag>
            <el-tag type="primary" v-if="scope.row.occupied==2">已占用</el-tag>
            <el-tag type="success" v-if="scope.row.occupied==4">已释放</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作"  align="center" >
          <template #default="scope">
            <template v-if="scope.row.occupied==1">
              <el-button
                size="small" 
                type="success" 
                @click="pass(scope.row.id,scope.row.occupied,2)"
                plain>
                通过
              </el-button>
              <el-button
                size="small"
                type="danger"
                plain
                @click="reject(scope.row.id,scope.row.occupied,4)">
                驳回
              </el-button>
            </template> 
            <template v-else-if="scope.row.occupied==2">
              <el-button type="success" 
                plain size="small"
                >
                已处理</el-button>
            </template>
            <template v-else-if="scope.row.occupied==4">
              <el-button type="success" 
                plain size="small"
                >
                已处理</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        background
        :page-count="tableData.pages"
        v-model:current-page="params.page"
        :total="tableData.total"
        :close-on-click-modal="false"
        @current-change="getTableData"
        style="margin-top:15px;"></el-pagination>
    </div>
    
    
  </div>

</template>

<script lang="ts" setup>
import parkingVue from '@/components/icons/CommunityIcon/parking.vue'
import Search from '@/components/icons/CommunityIcon/Search'
import Green from '@/components/icons/CommunityIcon/greencar'
import Red from '@/components/icons/CommunityIcon/redcar'
import Yellow from '@/components/icons/CommunityIcon/yellowcar'
import { ref, reactive ,onMounted, nextTick} from 'vue'
import { ElMessage,ElMessageBox ,ElTable} from 'element-plus'
import {_axios,post,get} from '@/plugins/axios'
import url from './util'
import Cul from './culculate'
import * as echarts from 'echarts'

// 区域选择相关
const areas = ref([
  { value: 'A', label: 'A区' },
  { value: 'B', label: 'B区' },
  { value: 'C', label: 'C区' },
  { value: 'D', label: 'D区' },
  { value: 'E', label: 'E区' }
])
const selectedArea = ref('A') // 默认选择A区

// 区域变更处理
const handleAreaChange = () => {
  getTableData1() // 重新获取对应区域的数据
  updateChart() // 更新图表数据
}

const input = ref('')
const formObj = null
const showDialog=ref(false)
const activeTab = ref('review') // 默认激活审核标签页
const chartInstance = ref(null) // 图表实例

const count=ref(0)//占用
const count1=ref(0)//空闲
const count2=ref(0)//审核
const t=ref(0)
const x=ref(0)
const y=ref(0)
const totalParkingSpaces = ref(0); // 新增：总车位数
const main=reactive({
  id:null,
  content:'',
  parkingId:'',
  username:'',
  carNumber:'',
  occupied:'',
  tableData: [],// 初始化为空数组
  kong:[],
  used:[],
  wait:[]
})

// 获取车位数据并按区域筛选
getTableData1()
function getTableData1 () {
  _axios.request({
    url: '/parkingSpace/list',
    method: 'get'
  }).then(response => {
    const data = response.data;
    // 筛选当前选择区域的车位
    const filteredData = data.filter(item => item.content.startsWith(selectedArea.value))
    
    totalParkingSpaces.value = filteredData.length; // 动态获取总车位数
    count.value = 0; // 重置 count
    main.used = []
    main.kong = []
    main.wait = []
    
    filteredData.forEach(item => {
      if (item.occupied === 2) {
        main.used.push(item.content);
        count.value++; 
      }
      if (item.occupied === 0||item.occupied === 3||item.occupied===4) {
        main.kong.push(item.content);
        count1.value++; 
      }
      if (item.occupied === 1) {
        main.wait.push(item.content);
        count2.value++; 
      }
    });
  })
}

const dialog = reactive({
  show: false,
  title: '',
  id: null
})
const tableData = reactive({
  records: [] ,// 初始化为空数组
  pages: 0,
  total: 0,
  allRecords:[]
});
const params = reactive({
    page: 1,
    limit: 8
})

// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('parkingChart')
  if (chartDom) {
    chartInstance.value = echarts.init(chartDom)
    updateChart()
  }
}

// 更新图表数据
const updateChart = () => {
  get('/parkingSpace/list1',null,content => {
    const records = content//不需要content.records作分页
    
    // 筛选当前选择区域的车位
    const filteredRecords = records.filter(item => item.content.startsWith(selectedArea.value))
    
    // 统计数据
    const stats = {
      free: 0,    // 空闲 (0或4或3)
      review:0,   // 审核(1)
      occupied: 0, // 占用 (2)
      total: filteredRecords.length // 直接使用 filteredRecords.length
    }
    
    filteredRecords.forEach(item => {
      if (item.occupied === 0 || item.occupied === 3||item.occupied === 4) {
        stats.free++
      } else if (item.occupied === 1 ) {
        stats.review++
      }
      else if (item.occupied === 2 ) {
        stats.occupied++
      }
    })
    
    // 设置图表选项
    const option = {
      title: {
        text: '车位状态统计',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['空闲车位', '审核中车位','占用车位']
      },
      series: [
        {
          name: '车位状态',
          type: 'pie',
          radius: ['40%', '80%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: stats.free, name: '空闲车位', itemStyle: { color: '#67C23A' } },
            { value: stats.review, name: '审核中车位', itemStyle: { color: '#eebb00' } },
            { value: stats.occupied, name: '占用车位', itemStyle: { color: '#F56C6C' } }
          ]
        }
      ]
    }
    
    chartInstance.value.setOption(option)
  })
}


getTableData()
function getTableData(){
  post('/parkingSpace/list2',{pageNo:params.page, pageSize:params.limit },content=>{
    // 这里修改：不再筛选数据，直接使用从后端获取的数据
    // 后端应该已经按区域筛选好了数据
    tableData.records = content.records
    tableData.pages = content.pages
    tableData.total = content.total
  })
  
    updateChart()
}

// 组件挂载时初始化图表
onMounted(() => {
  initChart()
  getTableData1()
})

const tccahng=reactive({
  id:null,
  content:'',
  parkingId:'',
  username:'',
  carNumber:'',
  occupied:''
})
function cul() {
  showDialog.value=true
  dialog.title = '车位统计'
  dialog.id = null
  dialog.show = true
}

const pass = (id,occupied,status) =>  {
  console.dir(status)
  let text=''
  if(occupied==1){text='确定通过该车位申请吗？'}
  else{text='车位状态不对为1'}
  ElMessageBox.confirm(
    text,'提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    post(url.pass, { id,occupied,status }, content => {
      getTableData()
    },formObj)
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消，请尽快处理',
    })
  })
}
const reject = (id,occupied,status) =>  {
  console.dir(status)
  let text=''
  if(occupied==1){text='确定驳回该车位申请吗？'}
  else if(occupied==2||occupied==4){text='确定重新处理该申请吗？'}
  else{text='申请已处理'}
  ElMessageBox.confirm(
    text,'提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    post(url.reject, { id,status }, content => {
      getTableData()
    },formObj)
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消，请尽快处理',
    })
  })
}
const search=()=>{
  console.dir(input.value)
  post(url.search, {input:input.value,pageNo:params.page, pageSize:params.limit}, content => {
    // 这里修改：不再筛选数据，直接使用从后端获取的数据
    tableData.records = content.records
    console.dir(tableData.records)
  },formObj)
}
</script>

<style scoped>
.tags-container {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
}

.tags-container .el-tag {
  flex: 0 0 calc(16.666% - 8px); /* 6个标签每行，考虑边距 */
  max-width: calc(16.666% - 8px);
  box-sizing: border-box;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.main3{
  width: 50%;
  margin-left: 1%;
  min-width: 0; /* 防止内容溢出 */
  
  background: #ffffff;
  border-radius: 4px;
  padding: 10px;
   box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.main2{
  width: 100%;
  margin-top: 2%;
  min-width: 0; /* 防止内容溢出 */
  
  background: #ffffff;
  border-radius: 4px;
  padding: 10px;
   box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
/* 新增样式 */
.chart-container {
  display: flex;
  width: 100%;
  height: 100%;
  gap: 20px; /* 左右区域间距 */
}

.chart-left {
  flex: 1; /* 占据剩余空间的70% */
  min-width: 0; /* 防止内容溢出 */
  background: #fff;
  border-radius: 4px;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-right {
  flex: 0.8; 
  background: #fff;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.legend-item {
  display: flex;
  align-items: center;
  margin: 10px 0;
}

.legend-color {
  display: inline-block;
  width: 16px;
  height: 16px;
  border-radius: 4px;
  margin-right: 8px;
}
.util{
  width: 100%;
  height: 60px;
  background-color: #ffffff;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 2px 2px 10px rgba(0,0,0,0.2);
  display: flex;
  align-items: center;
  .add-button{
    margin-left: 20px;
    margin-right: 809px;
  }
  span{
    font-size: 14px;
    margin-left: 20px;
  }
}
.main{
  width: 100%;
  padding: 15px;
  
  
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 2px 0px 10px rgba(0,0,0,0.2);
  overflow: hidden;
}
</style>